package com.intelligent.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.intelligent.dto.NoticeCreateDTO;
import com.intelligent.dto.NoticeDTO;
import com.intelligent.dto.NoticeQueryDTO;
import com.intelligent.entity.Notice;
import com.intelligent.service.NoticeService;
import com.intelligent.utils.Result;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 消息通知控制器
 */
@RestController
@RequestMapping("/notice")
public class NoticeController {

    @Autowired
    private NoticeService noticeService;

    /**
     * 创建通知
     */
    @PostMapping
    public Result<Integer> createNotice(@RequestBody @Validated NoticeCreateDTO createDTO) {
        Integer noticeId = noticeService.createNotice(createDTO);
        return Result.success(noticeId);
    }

    /**
     * 更新通知
     */
    @PutMapping("/update/{id}")
    public Result<Boolean> updateNotice(@PathVariable("id") Integer id, 
                                       @RequestBody @Validated NoticeCreateDTO createDTO) {
        createDTO.setNoticeId(id);
        Boolean result = noticeService.updateNotice(createDTO);
        return Result.success(result);
    }

    /**
     * 删除通知
     */
    @DeleteMapping("/delete/{id}")
    public Result<Boolean> deleteNotice(@PathVariable("id") Integer id) {
        Boolean result = noticeService.deleteNotice(id);
        return Result.success(result);
    }

    /**
     * 获取通知详情
     */
    @GetMapping("/detail/{id}")
    public Result<NoticeDTO> getNotice(@PathVariable("id") Integer id) {
        Notice notice = noticeService.getById(id);
        if (notice == null) {
            return Result.error("通知不存在");
        }
        NoticeDTO dto = convertToDTO(notice);
        return Result.success(dto);
    }

    /**
     * 分页查询通知列表
     */
    @PostMapping("/page")
    public Result<IPage<NoticeDTO>> pageNotices(NoticeQueryDTO queryDTO) {
        IPage<NoticeDTO> page = noticeService.pageNotices(queryDTO);
        return Result.success(page);
    }

    /**
     * 发布通知
     */
    @PostMapping("/{id}/publish")
    public Result<Boolean> publishNotice(@PathVariable("id") Integer id) {
        Boolean result = noticeService.publishNotice(id);
        return Result.success(result);
    }

    /**
     * 获取用户通知列表
     */
    @GetMapping("/user")
    public Result<IPage<NoticeDTO>> getUserNotices(NoticeQueryDTO queryDTO, HttpServletRequest request) {
        // 从请求中获取用户ID（这里需要根据实际的用户认证方式来获取）
        Long userId = getCurrentUserId(request);
        IPage<NoticeDTO> page = noticeService.getUserNotices(userId, queryDTO);
        return Result.success(page);
    }

    /**
     * 标记通知为已读
     */
    @PostMapping("/mark-read/{id}")
    public Result<Boolean> markAsRead(@PathVariable("id") Integer id, HttpServletRequest request) {
        Long userId = getCurrentUserId(request);
        Boolean result = noticeService.markAsRead(id, userId);
        return Result.success(result);
    }

    /**
     * 获取用户未读通知数量
     */
    @GetMapping("/unread-count")
    public Result<Integer> getUnreadCount(HttpServletRequest request) {
        Long userId = getCurrentUserId(request);
        Integer count = noticeService.getUnreadCount(userId);
        return Result.success(count);
    }



    /**
     * 获取通知统计信息
     */
    @GetMapping("/stats")
    public Result<Map<String, Object>> getStats(HttpServletRequest request) {
        Long userId = getCurrentUserId(request);
        Map<String, Object> stats = new HashMap<>();
        
        // 总通知数
        Integer totalNotices = noticeService.count();
        stats.put("totalNotices", totalNotices);
        
        // 未读通知数
        Integer unreadCount = noticeService.getUnreadCount(userId);
        stats.put("unreadCount", unreadCount);
        
        return Result.success(stats);
    }

    /**
     * 批量标记为已读
     */
    @PostMapping("/batch/read")
    public Result<Boolean> batchMarkAsRead(@RequestBody List<Integer> noticeIds, HttpServletRequest request) {
        Long userId = getCurrentUserId(request);
        Boolean result = noticeService.batchMarkAsRead(noticeIds, userId);
        return Result.success(result);
    }

    /**
     * 从请求中获取当前用户ID
     * 这里需要根据实际的认证方式来实现
     */
    private Long getCurrentUserId(HttpServletRequest request) {
        // 这里应该从JWT token或session中获取用户ID
        // 暂时返回固定值，实际项目中需要实现
        String userIdStr = request.getHeader("userId");
        if (userIdStr != null) {
            return Long.valueOf(userIdStr);
        }
        return 1L; // 默认用户ID
    }

    /**
     * 转换为DTO
     */
    private NoticeDTO convertToDTO(Notice notice) {
        NoticeDTO dto = new NoticeDTO();
        BeanUtils.copyProperties(notice, dto);
        return dto;
    }
}